/*脚本里面封装了增删改查请求的方法*/

import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import settings from '@/settings'

const tokenName = settings.tokenName
const iamLoginUrl = process.env.VUE_APP_BASE_API + '/login/iam-login'

// 创建axios异步请求实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests支持cookie
  timeout: 600000 // 请求超时时间
})

// 请求前进行拦截
service.interceptors.request.use(
  config => {
    // 判断store中是否存在token
    if (store.getters.token) {
      // 调用@/utils/auth中getToken()，获取token信息，并将token添加到header头部信息中
      config.headers[tokenName] = getToken()
    }
    // 返回配置
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// 响应时拦截
service.interceptors.response.use(
  response => {
    const { request } = response
    // 获取后端返回的数据
    const res = response.data

    if (res.code !== 0) {
      if (res.code === 401) {
        if (request.responseURL.endsWith('/personal/check-token')) {
          location.href = iamLoginUrl
          return Promise.reject(new Error('您的登录已经失效'))
        }

        if (settings.debug) {
          // 重新登录
          MessageBox.confirm('您的登录已经失效，请重新登录', '系统提示', {
            confrimButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
              // document.location = 'http://authserver.cqipc.edu.cn/authserver/login?service=https%3A%2F%2Fzhty.cqipc.edu.cn%3A8187%2Fwebpc'
            })
          })
        } else {
          location.reload()
          // document.location = 'http://authserver.cqipc.edu.cn/authserver/login?service=https%3A%2F%2Fzhty.cqipc.edu.cn%3A8187%2Fwebpc'
        }
      } else {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
